import axios from 'axios';

// 创建axios实例
const apiClient = axios.create({
  baseURL: 'http://localhost:8000/api/', // Django API的基础URL
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    // 这里可以添加认证token等
    const token = getAuthToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    // 处理错误
    console.error('API Error:', error);
    return Promise.reject(error);
  }
);

// 认证相关API
export const authAPI = {
  login: (credentials: { username: string; password: string }) => {
    return apiClient.post('auth/login/', credentials);
  },
  register: (userData: { username: string; password: string; email: string }) => {
    return apiClient.post('auth/register/', userData);
  },
  logout: () => {
    return apiClient.post('auth/logout/');
  },
  getCurrentUser: () => {
    return apiClient.get('auth/user/');
  },
};

// 示例数据API
export const dataAPI = {
  getItems: (page: number = 1, limit: number = 10) => {
    return apiClient.get(`items/?page=${page}&limit=${limit}`);
  },
  getItemById: (id: string) => {
    return apiClient.get(`items/${id}/`);
  },
  createItem: (itemData: any) => {
    return apiClient.post('items/', itemData);
  },
  updateItem: (id: string, itemData: any) => {
    return apiClient.put(`items/${id}/`, itemData);
  },
  deleteItem: (id: string) => {
    return apiClient.delete(`items/${id}/`);
  },
};

// 辅助函数
export const setAuthToken = (token: string) => {
  try {
    // 在实际应用中，应该使用安全的存储方式，如expo-secure-store
    localStorage.setItem('authToken', token);
  } catch (error) {
    console.error('Failed to store auth token:', error);
  }
};

export const getAuthToken = () => {
  try {
    // 在实际应用中，应该使用安全的存储方式，如expo-secure-store
    return localStorage.getItem('authToken');
  } catch (error) {
    console.error('Failed to get auth token:', error);
    return null;
  }
};

export default apiClient;